package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.vo.CourseCategoryTreeVo;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    /**
     * 课程分类树形结构查询
     * @param id
     * @return
     */
    @Override
    public List<CourseCategoryTreeVo> queryTreeNodes(String id) {

        // 调用mapper递归查询分类信息
        List<CourseCategoryTreeVo> courseCategoryTreeVos = courseCategoryMapper.selectTreeNodes(id);

        // 找到每个节点的子节点，最终封装成List<CourseCategoryTreeVo>
        // 先将list转成map，key就是节点的id，value就是CourseCategoryTreeVo对象，目的就是为了方便从map获取节点，filter(item -> !id.equals(item.getId()))把根节点排除
        Map<String, CourseCategoryTreeVo> mapTemp = courseCategoryTreeVos.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        List<CourseCategoryTreeVo> categoryTreeVoList = new ArrayList<>();
        // 从头遍历 List<CourseCategoryTreeVo> ，一边遍历一边找子节点放在父节点的ChildrenTreeNodes
        courseCategoryTreeVos.stream().filter(item -> !id.equals(item.getId())).forEach(item -> {
            // 向list写入元素
            if(item.getParentid().equals(id)) {
                categoryTreeVoList.add(item);
            }
            // 找到子节点的父节点
            CourseCategoryTreeVo courseCategoryParent = mapTemp.get(item.getParentid());
            if(courseCategoryParent != null) {
                if(courseCategoryParent.getChildrenTreeNodes() == null) {
                    // 如果该父节点的ChildrenTreeNodes属性为空要new一个集合，因为要向该集合中放它的子节点
                    courseCategoryParent.setChildrenTreeNodes(new ArrayList<>());
                }
                // 找到每个子节点放在父节点的ChildrenTreeNodes属性中
                courseCategoryParent.getChildrenTreeNodes().add(item);
            }
        });

        return categoryTreeVoList;
    }
}
